package com.byit.service.impl;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.byit.domain.quartz.Job;
import com.byit.mapper.JobMapper;
import com.byit.service.IJobService;
import com.byit.utils.*;
import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.List;

/**
 * 定时任务调度信息 服务层
 * 
 * @author morej
 */
@Service
public class JobServiceImpl extends ServiceImpl<JobMapper, Job> implements IJobService {

	@Autowired
	private Scheduler scheduler;

	/**
	 * 项目启动时，初始化定时器
	 */
	@PostConstruct
	public void init() {
		EntityWrapper<Job> wrapper = new EntityWrapper<>();
		wrapper.setSqlSelect("*");
		wrapper.and("is_del",0);
		List<Job> jobList = this.baseMapper.selectList(wrapper);
		for (Job job : jobList) {
			CronTrigger cronTrigger = ScheduleUtils.getCronTrigger(scheduler,
					job.getJobId());
			// 如果不存在，则创建
			if (cronTrigger == null) {
				ScheduleUtils.createScheduleJob(scheduler, job);
			} else {
				ScheduleUtils.updateScheduleJob(scheduler, job);
			}
		}
	}

	/**
	 * 暂停任务
	 * 
	 * @param job
	 *            调度信息
	 */
	@Override
	public int pauseJob(Job job) {
		job.setStatus(ScheduleConstants.Status.PAUSE.getValue());
		int rows = this.baseMapper.updateById(job);
		if (rows > 0) {
			ScheduleUtils.pauseJob(scheduler, job.getJobId());
		}
		return rows;
	}

	/**
	 * 恢复任务
	 * 
	 * @param job
	 *            调度信息
	 */
	@Override
	public int resumeJob(Job job) {
		job.setStatus(ScheduleConstants.Status.NORMAL.getValue());
		job.setUpdateTime(new Date());
		int rows = this.baseMapper.updateById(job);
		if (rows > 0) {
			ScheduleUtils.resumeJob(scheduler, job.getJobId());
		}
		return rows;
	}

	/**
	 * 删除任务后，所对应的trigger也将被删除
	 * 
	 * @param job
	 *            调度信息
	 */
	@Override
	public int deleteJob(Job job) {
		int rows = this.baseMapper.deleteById(job.getJobId());
		if (rows > 0) {
			ScheduleUtils.deleteScheduleJob(scheduler, job.getJobId());
		}
		return rows;
	}

	/**
	 * 批量删除调度信息
	 * 
	 * @param ids
	 *            需要删除的数据ID
	 * @return 结果
	 */
	@Override
	public void deleteJobByIds(String ids) {
		Long[] jobIds = ConvertUtil.toLongArray(ids);
		for (Long jobId : jobIds) {
//			Job job = this.baseMapper.selectById(jobId);
//			deleteJob(job);
			Job job = new Job();
			job.setJobId(jobId);
			job.setIsDel(1);
			job.setUpdateTime(new Date());
            if(updateById(job)){
                ScheduleUtils.deleteScheduleJob(scheduler, job.getJobId());
            }
        }
	}

	/**
	 * 任务调度状态修改
	 * 
	 * @param job
	 *            调度信息
	 */
	@Override
	public int changeStatus(Job job) {
		int rows = 0;
		String status = job.getStatus();
		if (ScheduleConstants.Status.NORMAL.getValue().equals(status)) {
			rows = resumeJob(job);
		} else if (ScheduleConstants.Status.PAUSE.getValue().equals(status)) {
			rows = pauseJob(job);
		}
		return rows;
	}

	/**
	 * 立即运行任务
	 * 
	 * @param job
	 *            调度信息
	 */
	@Override
	public int run(Job job) {
		return ScheduleUtils.run(scheduler, this.baseMapper.selectById(job.getJobId()));
	}

	/**
	 * 新增任务
	 * 
	 * @param job
	 *            调度信息 调度信息
	 */
	@Override
	public int addJobCron(Job job) {
		job.setCreateTime(new Date());
		job.setStatus(ScheduleConstants.Status.PAUSE.getValue());
		int rows = this.baseMapper.insert(job);
		if (rows > 0) {
			ScheduleUtils.createScheduleJob(scheduler, job);
		}
		return rows;
	}

	/**
	 * 更新任务的时间表达式
	 * 
	 * @param job
	 *            调度信息
	 */
	@Override
	public int updateJobCron(Job job) {
		int rows = this.baseMapper.updateById(job);
		if (rows > 0) {
			ScheduleUtils.updateScheduleJob(scheduler, job);
		}
		return rows;
	}

	/**
	 * 保存任务的时间表达式
	 * 
	 * @param job
	 *            调度信息
	 */
	@Override
	public int saveJobCron(Job job) {
		Long jobId = job.getJobId();
		int rows = 0;
		if (StringUtil.isNotNull(jobId)) {
			rows = updateJobCron(job);
		} else {
			rows = addJobCron(job);
		}
		return rows;
	}
}